<template>
    <div class="container">
        <!-- 导航栏区域开始 -->
        <TridentNavBar>
            <template #left><i class="iconfont icon-zuojiantou"></i></template>
            <template #default>选择联系人</template>
            <template #right>
                <span @click="handleJoinGroupChat" style="border: 1px solid #fff;padding: 5px 12px;border-radius: 6px;">完成</span>
            </template>
        </TridentNavBar>
        <!-- 导航栏区域结束 -->

        <!-- 搜索区域开始 -->
        <van-search
            v-model="params.username"
            show-action
            placeholder="搜索"
            class="search-wrap"
        >
            <template #action>
                <div @click="handleSearch">搜索</div>
            </template>
        </van-search>
        <!-- 搜索区域结束 -->

        <!-- 联系人区域开始 -->
         <div class="contact-wrap">
            <van-index-bar
                :sticky-offset-top="100"
                highlight-color="#27BA9B"
                :sticky="true"
                :index-list="Object.keys(contactList)"
            >
                <div class="contact-box" v-for="(key, index) in Object.keys(contactList)" :key="index">
                    <van-index-anchor :index="key"/>
                    <div class="contact-item" v-for="(value, index) in contactList[key]" :key="index">
                        <van-checkbox v-model="value.is_check" @change="handleChange($event, value.info.uid)" :disabled="value.disabled" checked-color="#27BA9B"/>
                        <div class="image-panel">
                            <van-image
                                width="50"
                                height="50"
                                :src="value.info.avatar_url ? global.MINIO_FILE_DOMAIN + value.info.avatar_url : 'src/assets/images/default_avatar.png'"
                                fit="contain"
                            />
                        </div>
                        <div class="name-panel">{{value.info.username}}</div>
                    </div>
                </div>
            </van-index-bar>

            <!-- 返回顶部区域开始 -->
            <van-back-top bottom="100" right="10"><i class="iconfont icon-top" style="font-size: 30px;"></i></van-back-top>
         </div>
        <!-- 联系人区域结束 -->
    </div>
</template>

<script lang="ts" setup>
import { reqFriendListAPI } from '@/apis/friend'
import { reqGroupChatDetailAPI, reqJoinGroupChatAPI } from '@/apis/groupChat'
import type { FriendListParams } from '@/types/friend'
import type { GroupChat, JoinGroupChatParams } from '@/types/groupChat'
import { pinyin } from 'pinyin-pro'
import { showSuccessToast, showToast } from 'vant'
import { inject, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// 全局属性
const global: any = inject('global')

// 路由
const route = useRoute()

// 路由器
const router = useRouter()

// 联系人
const contactList: any = ref({})

onMounted(async () => {
    await getGroupChatInfo()
    await getContactList()
})

// -------------- 处理复选框变化开始 --------------
const handleChange = (e: any, uid: string) => {
    let uids = joinGroupChatParams.value.uids ? joinGroupChatParams.value.uids.split(',') : []

    if (e) {
        uids.push(uid)
    } else {
        const index = uids.findIndex(item => item == uid)
        uids.splice(index, 1)
    }

    joinGroupChatParams.value.uids = uids.join()
}
// -------------- 处理复选框变化结束 --------------



// -------------- 处理联系人列表开始 --------------
const params = ref<FriendListParams>({
    username: '',
    is_my_friend: 1,
    is_friend_info: 1,
    status: '1',
    page: 1,
    page_size: -1
})

// 获取联系人列表
const getContactList = async () => {
    const result = await reqFriendListAPI(params.value)
    let tempFriendList: any = {}
    result.data.friends.forEach(item => {
        // 判断当前联系人列表中是否存在群聊成员
        groupChat.value?.member.forEach(member => {
            if (item.info.uid == member.uid) {
                item.is_check = true
                item.disabled = true
            }
        });
        let initial = pinyin(item.info.username, {pattern: 'first', toneType: 'none' }).substr(0, 1).toLocaleUpperCase()
        
        if (!tempFriendList[initial]) {
            tempFriendList[initial] = []
        }

        tempFriendList[initial].push(item)
    })

    contactList.value = Object.keys(tempFriendList).sort().reduce((acc: any, key) => {
        acc[key] = tempFriendList[key];
        return acc;
    }, {});
}
// -------------- 处理联系人列表结束 --------------



// --------------- 处理群聊信息开始 ---------------
// 群聊信息
const groupChat = ref<GroupChat>()

// 获取群聊信息
const getGroupChatInfo = async () => {
    const result = await reqGroupChatDetailAPI(route.query.gid as never)
    groupChat.value = result.data
}
// --------------- 处理群聊信息结束 ---------------



// -------------- 处理搜索联系人开始 --------------
// 搜索联系人
const handleSearch = () => {
    getContactList()
}
// -------------- 处理搜索联系人结束 --------------



// --------------- 处理加入群聊开始 ---------------
const joinGroupChatParams = ref<JoinGroupChatParams>({
    gid: route.query.gid as never,
    uids: ''
})

// 加入群聊
const handleJoinGroupChat = async () => {
    if (joinGroupChatParams.value.uids == '') {
        showToast('请选择联系人')
        return false
    }
    await reqJoinGroupChatAPI(joinGroupChatParams.value)
    showSuccessToast('加入群聊成功')
    setTimeout(() => {
        router.push('chatInfo?mode=2&gid=' + route.query.gid)
    }, 1000)
}
// --------------- 处理加入群聊结束 ---------------
</script>

<style scoped lang="scss">
page,
.container {
    height: 100vh;

    // 搜索区域开始
    .search-wrap {
        position: fixed;
        top: 45px;
        left: 0;
        width: 100%;
        z-index: 100;
    }

    // 联系人区域开始
    .contact-wrap {
        margin-top: 108px;
        padding-bottom: 10px;
        .contact-box {
            padding-left: 10px;
            padding-right: 20px;
            .contact-item {
                background-color: #fff;
                display: flex;
                align-items: center;
                padding-left: 4px;
                border-radius: 6px;
                &:last-child .name-panel {
                    border-bottom: none;
                }
                .image-panel {
                    width: 45px;
                    height: 45px;
                    line-height: 45px;
                    border-radius: 5px;
                    text-align: center;
                    overflow: hidden;
                    margin-left: 15px;
                    img {
                        width: 80px;
                        height: 80px;
                    }
                }
                .name-panel {
                    flex: 1;
                    margin-left: 15px;
                    color: #000;
                    font-size:14px;
                    border-bottom: 1px solid #EDEDED;
                    padding: 25px 0;
                }
            }
        }
    }
}
</style>